package com.szt.sy.config.swagger;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.common.collect.Lists;
import com.szt.sy.config.ApplicationConfig;
import com.szt.sy.vo.rep.base.ResultCode;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/***
 * swagger 配置类
 * 
 * @author wwy
 *
 */
@ConditionalOnProperty(prefix = "application.swagger", value = "enable", havingValue = "true", matchIfMissing = false)
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
	
	@Autowired
	private ApplicationConfig applicationConfig;
	
	@Bean
	public Docket createRestApi() {
		List<ResponseMessage> responseMessages = Lists.newArrayList();
		for (ResultCode resultCode : ResultCode.values()) {
			responseMessages
					.add(new ResponseMessageBuilder().code(resultCode.getCode()).message(resultCode.getMes()).build());
		}
		return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).useDefaultResponseMessages(false)
				.globalResponseMessage(RequestMethod.GET, responseMessages)
				.ignoredParameterTypes(HttpSession.class, HttpServletRequest.class, HttpServletResponse.class).select()
				.apis(RequestHandlerSelectors.basePackage(applicationConfig.getBasePackage() + ".controller.api"))
				.paths(PathSelectors.any()).build();
		
	}
	
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder().title(applicationConfig.getSwagger().getTitle())
				.description(applicationConfig.getSwagger().getDesc())
				.version(applicationConfig.getSwagger().getVersion()).build();
	}
	
}
